<template>
  <div ref="chart" :style="{ width: width, height: height }"></div>
</template>

<script>
import * as echarts from 'echarts'
import { debounce } from '@/utils'
import chinaMap from '@/assets/map/china.json'

export default {
  name: 'MapChart',
  props: {
    chartData: {
      type: Object,
      required: true
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) return
    window.removeEventListener('resize', this.resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      echarts.registerMap('china', chinaMap)
      this.chart = echarts.init(this.$refs.chart)
      this.setOptions(this.chartData)
    },
    setOptions({ data } = {}) {
      if (!this.chart) return
      
      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b}<br/>用户数: {c}'
        },
        visualMap: {
          min: 0,
          max: Math.max(...data.map(item => item.value), 100),
          text: ['高', '低'],
          realtime: false,
          calculable: true,
          inRange: {
            color: ['#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695']
          }
        },
        series: [
          {
            name: '用户分布',
            type: 'map',
            map: 'china',
            roam: true,
            emphasis: {
              label: {
                show: true
              }
            },
            data: data || []
          }
        ]
      })
    },
    resizeHandler: debounce(function() {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
  }
}
</script>